package pl.com.like.sequoia.maintenance;

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashSet;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class DirScanner implements IDirScanner {

	Logger log = LoggerFactory.getLogger(DirScanner.class);

	private final Set<File> files = new HashSet<File>();

	/** {@inheritDoc} */
	public Set<File> scan(File basedir) {
		if (log.isDebugEnabled()) {
			log.debug("start scanning directory {}", basedir.getAbsolutePath());
		}
		scanRoot(basedir);
		return files;
	}

	public void scanRoot(File dir) {
		for (final File fItem : dir.listFiles()) {
			try {
				if (fItem.getAbsolutePath().equals(fItem.getCanonicalPath())) {
					if (fItem.isDirectory()) {
						scanRoot(fItem);
					} else {
						files.add(fItem);
					}
				}
			} catch (IOException e) {
				String msg = MessageFormat.format("could not read/scan file/directory {0}", fItem.getAbsolutePath());
				log.error(msg, e);
			}
		}
	}

}
